/// <reference path="../typings/node/node.d.ts"/>

var fs = require('fs');
var path = require('path');

var bluebird = require('bluebird');

var express = require('express');
// var crawler = require('./crawler');

var app = express();

// serve static files.
app.use(express.static('public', {
	dotfiles: 'ignore',
	etag: false
}));

fs.readdir(path.join(__dirname, 'crawlers'), function (err, files) {
	if (err) {
		return console.error(err);
	}
	files.forEach(function (file) {
		var crawler = require(path.join(__dirname, 'crawlers', file));
		Object.keys(crawler).forEach(function (k) {
			var url = '/' + file.slice(0, file.lastIndexOf('.')) + '/' + k + '.json';
			app.get(url, function (req, res) {
				crawler[k]().then(function (news) {
					res.jsonp(news);
				}).catch(function (err) {
					res.status(500).jsonp({err: 500, message: err});
				});
			});
			console.log('Route at `' + url + '`.');
		});
	})
});

module.exports = app;

app.listen(3000, function () {
	console.log('Running...');
});